<!-- src/components/OrderList.vue -->
<template>
  <div class="order-list">
    <h2>订单列表</h2>
    <table class="styled-table">
      <thead>
      <tr>
        <th>订单编号</th>

        <th>服务名</th>
        <th>订单状态</th>
        <th>订单定金</th>
        <th>订单尾款</th>
        <th>订单创建日期</th>
        <th>订单开始服务时间</th>
        <th>订单结束服务时间</th>
        <th>地址联系人名称</th>
        <th>电话</th>
        <th>操作</th>

      </tr>
      </thead>
      <tbody>
      <tr v-for="(order, index) in responseData" :key="index">
        <td>{{order.orderId}}</td>

        <td>{{ order.serviceMainName }}</td>
        <td>{{ order.orderStatus }}</td>
        <td>{{order.orderStartMoney}}</td>
        <td>{{ order.orderEndMoney }}</td>
        <td>{{ order.orderDateTime}}</td>
        <td>{{ order.orderStartTime }}</td>
        <td>{{ order.orderEndTime }}</td>
        <td>{{ order.addressLinkman}}</td>
        <td>{{ order.addressPhone }}</td>
        <td>
          <button :id="order.addressId" class="btn btn-delete" v-if="order.orderStatus=== '待付订金' " @click="deleteAddress(order.orderId)">
            取消订单
          </button>
          <button :id="order.addressId" class="btn btn-delete" v-if="order.orderStatus=== '待付订金'" @click="submitForm(order)">
            支付订金
          </button>
          <button :id="order.addressId" class="btn btn-delete" v-if="order.orderStatus=== '待付尾款'" @click="submitForm(order)">
            支付尾款
          </button>
          <button :id="order.addressId" class="btn btn-delete" v-if="order.orderStatus=== '待评价'" @click="deleteAddress(order.orderId)">
            评价订单
          </button>

        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>import { BASE_URL } from "@/util/Config.js";
import { useUserStore } from '@/stores/user';
import { mapState } from 'pinia';
import { onMounted } from "vue";

export default {
  setup() {
    const userStore = useUserStore();

    return {
      userStore
    };
  },
  data() {
    return {
      responseData: []
    };
  },
  computed: {
    // ✅ 正确方式：使用 mapState 获取 store 数据
    ...mapState(useUserStore, ['isLoggedIn']),
    ...mapState(useUserStore, {
      userId: (store) => store.userInfo?.userId,
      username: (store) => store.userInfo?.username
    })
  },
  methods: {

    async sendData() {
      const userId = this.userStore.userInfo?.userId;
      const data = { userId: userId };

      try {
        const response = await fetch(BASE_URL + '/orders', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        });
        const responseData = await response.json();
        this.responseData = responseData.data;
      } catch (error) {
        console.error('请求出错:', error);
      }
    },
    async deleteAddress(addressId){
      const userId = this.userStore.userInfo?.userId;
      if(confirm('确定要取消该订单吗？')){


        try {
          const id = addressId;
          const response = await fetch(BASE_URL+`/my/orders/${id}/cancel`, {
            method: 'Put',
            headers: {
              'Content-Type': 'application/json',
              'X-User-ID':userId
            },

          });

          if (!response.ok) {
            console.log('删除成功')

          }

          const responseData = await response.json();
          this.responseData = responseData.data; // 更新组件的 data 属性
          console.log(responseData);
          // 处理响应数据
        } catch (error) {
          console.error('There was an error!', error);
        }
        this.sendData()
      }

      // 调用 API 删除该地址
    },
    async submitForm(order) {
      const id = this.$route.params.id;
      const userId = this.userStore.userInfo.userId;

      // 2. 构造 JSON 数据
      const jsonData = {
          orderStatus:order.orderStatus,
          orderStartMoney:order.orderStartMoney,
          orderEndMoney:order.orderEndMoney,
          orderId:order.orderId,
      };

      try {

        // 4. 发送第二个请求：调起支付
        const payResponse = await fetch(BASE_URL + '/api/alipay/pay', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(jsonData),
          credentials: 'include'
        });

        if (!payResponse.ok) {
          throw new Error('支付请求失败');
        }

        const payResultText = await payResponse.text(); // 获取响应文本

        // 创建一个 div 来容纳返回的表单
        const formContainer = document.createElement('div');
        formContainer.innerHTML = payResultText;
        document.body.appendChild(formContainer);

        // 获取并提交表单
        const form = formContainer.querySelector('form');
        if (form) {
          form.submit(); // 自动跳转支付页面
        } else {
          throw new Error('未找到支付表单');
        }

        // 6. 标记为已提交
        this.submitted = true;

      } catch (error) {
        console.error('请求失败:', error);
        alert('操作失败，请重试');
      }
    },

  },
  watch: {
    isLoggedIn: {
      handler(newVal) {
        if (newVal) {
          this.sendData();
        }
      },
      immediate: true
    },
    userId: {
      handler(newVal) {
        if (newVal) {
          this.sendData();
        }
      },
      immediate: true
    }
  },
  mounted() {
    // 如果 userId 已经存在，直接发送请求
    if (this.userId) {
      this.sendData();
    }
  }
};
</script>

<style scoped>.order-list {
  padding: 20px;
}

.styled-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.styled-table th,
.styled-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.styled-table thead tr {
  background-color: #1abc9c;
  color: white;
}

.status-pending {
  color: orange;
  font-weight: bold;
}

.status-in-progress {
  color: blue;
}

.status-completed {
  color: green;
}
</style>